﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;

namespace NanoMvvm.ComponentModel
{
    public class RelayPropertyDescriptor : WrapperPropertyDescriptorBase
    {
        public RelayPropertyDescriptor(PropertyDescriptor root)
            : base(root)
        {
            var pi = root.ComponentType.GetProperty(root.Name);

            var getter = pi.GetGetMethod(true);

            if (getter != null)
            {
                PropertyGetter = PropertyHelper.CreateOpenGetter(pi);
            }

            var setter = pi.GetSetMethod(true);

            if (setter != null)
            {
                PropertySetter = PropertyHelper.CreateOpenSetter(pi);
            }
        }

        protected Func<object, object> PropertyGetter { get; private set; }

        protected Action<object, object> PropertySetter { get; private set; }

        public override object GetValue(object component)
        {
            if (PropertyGetter != null)
            {
                return PropertyGetter(component);
            }

            throw new InvalidOperationException("No getter defined.");
        }

        public override void SetValue(object component, object value)
        {
            if (PropertySetter != null)
            {
                PropertySetter(component, value);
            }
            else
            {
                throw new InvalidOperationException("No setter defined.");
            }
        }
    }
}